//
//  MYGShareAddFileView.swift
//  MYDoctor
//
//  Created by Denny on 2024/4/24.
//

import UIKit
import TZImagePickerController

class MYGShareAddFileView: UIView {
    var tapNextCompletion:(()->Void)?
    var tapCloseCompletion:(()->Void)?
    var farmerModel = MYCloudDiskContentModel()
    var dataSource = [MYGCloudDiskCommonShareModel]()
    lazy var tableView: UITableView = {
        let control = UITableView()
        control.register(UINib.init(nibName: "MYGCloudDiskCommonShareCell", bundle: nil), forCellReuseIdentifier: "MYGCloudDiskCommonShareCell")
        control.dataSource = self
        control.delegate = self
        control.separatorStyle = .none
        control.tableHeaderView = self.headerView
        control.rowHeight = 58
        return control
    }()
    
    var titleLB:UILabel = {
        let control = UILabel()
        control.text = "共享"
        control.font = .regular(18)
        control.textAlignment = .center
        control.textColor = .black
        return control
    }()
    
    lazy var backBtn:UIButton = {
        let control = UIButton()
        control.setImage(UIImage.init(named: "MYG_cloudDisk_add_close"), for: .normal)
        control.addTarget(self, action: #selector(tapClose), for: .touchUpInside)
        return control
    }()
    var headerView: MYGCloudDiskCommonHeaderView = {
        let control = Bundle.main.loadNibNamed("MYGCloudDiskCommonHeaderView", owner: nil)?.first as! MYGCloudDiskCommonHeaderView
        control.frame = CGRect.init(x: 0, y: 0, width: screenWidth, height: 170)
        return control
    }()
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .white
        addSubview(titleLB)
        titleLB.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(statusBarHeight)
            make.height.equalTo(navHeight)
        }
        addSubview(backBtn)
        backBtn.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.top.equalToSuperview().offset(statusBarHeight)
            make.height.equalTo(navHeight)
            make.width.equalTo(40)
        }
        addSubview(self.tableView)
        self.tableView.snp.makeConstraints { make in
            make.top.equalTo(titleLB.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
        self.headerView.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.height.equalTo(170)
            make.width.equalTo(screenWidth)
            make.centerX.equalToSuperview()
            
        }
        configDataSource()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc func tapClose() {
        if let c = self.tapCloseCompletion {
            c()
        }
    }
    
    func pushToCommonFileVC() {
        DispatchQueue.main.async {[weak self] in
            guard let `self` = self else {return}
            if let c = self.tapNextCompletion {
                c()
            }
        }
    }
    
    func configDataSource() {
        dataSource.append(setDataModel(title: "上传照片", iconName: "MYG_cloudDisk_commonshare_pic"))
        dataSource.append(setDataModel(title: "上传视频", iconName: "MYG_cloudDisk_commonshare_video"))
        dataSource.append(setDataModel(title: "上传文件", iconName: "MYG_cloudDisk_commonshare_file"))
        dataSource.append(setDataModel(title: "新建文件夹", iconName: "MYG_cloudDisk_commonshare_creatfile"))
        self.tableView.reloadData()
    }
    
    func setDataModel(title:String,iconName:String)->MYGCloudDiskCommonShareModel {
        var model = MYGCloudDiskCommonShareModel()
        model.iconName = iconName
        model.title = title
        return model
    }
}
extension MYGShareAddFileView:UITableViewDataSource,UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MYGCloudDiskCommonShareCell", for: indexPath) as! MYGCloudDiskCommonShareCell
        let model = self.dataSource[indexPath.row]
        cell.bindData(model)
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        guard let picker = TZImagePickerController.init(maxImagesCount: 9, columnNumber: 4, delegate: self, pushPhotoPickerVc: false) else {return}
        picker.modalPresentationStyle = .fullScreen
        
        if indexPath.row == 0 {
            picker.allowTakeVideo = false
            picker.allowPickingVideo = false
            picker.allowPickingImage = true
            self.rootResponsder().present(picker, animated: true)
        }
        if indexPath.row == 1 {
            picker.allowPickingVideo = true
            picker.allowPickingImage = false
            self.rootResponsder().present(picker, animated: true)
        }
        if indexPath.row == 2 {
            presentDocumentCloud()
        }
        
        if indexPath.row == 3 {
            MYGCloudDiskPopManager.showShareCreatNewFileAlert(self, pid: self.farmerModel.id) {[weak self] in 
                DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
                    self?.pushToCommonFileVC()
                })
            }
        }
    }
    
    func presentDocumentCloud() {
        let documentTypes = [
            "public.content",
            "public.source-code",
            "public.image",
            "public.audiovisual-content",
            "com.adobe.pdf",
            "com.apple.keynote.key",
            "com.microsoft.word.doc",
            "com.microsoft.excel.xls",
            "com.microsoft.powerpoint.ppt"
        ]
        
        let documentPickerViewController = UIDocumentPickerViewController(documentTypes: documentTypes, in: .import)
        documentPickerViewController.delegate = self
        self.rootResponsder().present(documentPickerViewController, animated: true, completion: nil)
    }
    
}

//照片、视频
extension MYGShareAddFileView: TZImagePickerControllerDelegate {
    //视频
    func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingVideo coverImage: UIImage!, sourceAssets asset: PHAsset!) {
        TZImageManager().requestVideoURL(with: asset) {[weak self] url in
            guard let url = url, let data = try? Data(contentsOf: url) else {return}
            guard let `self` = self else {return}
           
            MYGUploadManager.shared.addUploadTask(fileData: data, fileName: "\(Int(Date().timeIntervalSince1970)).mp4", type: .video, fid: Int(self.farmerModel.id) ?? 0)
            self.pushToCommonFileVC()
            
        } failure: { params in
            print("视频获取失败")
        }
        DispatchQueue.main.async(execute: {
            picker.dismiss(animated: true, completion: nil)
        })
    }
    //照片
    func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingPhotos photos: [UIImage]!, sourceAssets assets: [Any]!, isSelectOriginalPhoto: Bool, infos: [[AnyHashable : Any]]!) {
        guard let pics = photos.first else {
            return
        }
        guard let imageData = pics.jpegData(compressionQuality: 0.1) else {return}
        MYGUploadManager.shared.addUploadTask(fileData: imageData, fileName: "\(Int(Date().timeIntervalSince1970)).png", type: .image, fid: Int(self.farmerModel.id) ?? 0)
        
        DispatchQueue.main.async(execute: {[weak  self] in
            picker.dismiss(animated: true, completion: nil)
            guard let `self` = self else {return}
            self.pushToCommonFileVC()
        })
    }
}

//系统文件
extension MYGShareAddFileView : UIDocumentPickerDelegate {
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
        let components = url.absoluteString.components(separatedBy: "/")
        if let name = components.last,let  fileName = name.removingPercentEncoding {
            ICouldManager.downloadFile(WithDocumentUrl: url) {[weak self] (fileData) in
                guard let `self` = self else {return}
                MYGUploadManager.shared.addUploadTask(fileData: fileData, fileName: fileName, type: .file, fid:Int(self.farmerModel.id) ?? 0 )
                self.pushToCommonFileVC()
            }
        }
       
    }
}
struct MYGCloudDiskCommonShareModel {
    var title = ""
    var iconName = ""
}
